<?php
/**
 * @version			$Id$
 * @author			Richard Asp
 * @package			Joomla
 * @subpackage		gnudoor
 * @copyright		(C) 2010 gnudoor LLC
 * @license      GNU/GPL, see LICENSE.php
 * Joomla! is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 * See COPYRIGHT.php for copyright notices and details.
 */

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport('joomla.application.component.controller');

class GnudoorControllerAppointments extends JController
{
	public $timezone;
	public $events;
	public $kTimeslots;
	public $summary;
	public $dtend;
	public $dtstart;
	public $recurring;
	public $description;
	
	
	
	function __construct() {
	    parent::__construct();
	    
	    // Register Extra tasks
	    $this->registerTask( 'add','edit' );
	}
	
	function display_week() {
        JRequest::setVar( 'view', 'appointments' );
		JRequest::setVar( 'layout', 'default_week');
		parent::display();
    }
	
	
    function display() {
    		
		global $timezone;
    	$dateparam = JRequest::getVar('date');
		if ($dateparam) {
			JRequest::setVar('dateparam',$dateparam);
		}

		$model =& $this->getModel('Appointments');
		$kTimeslots = $model->getSlots();		
		$cals = $model->getCals();
		$kTreatments = $model->getTreats();
		$config = $model->getConfigs();
		$customfields = $model->getFields();
		JRequest::setVar('customfields',$customfields);

require_once ( JPATH_BASE .DS.'components'.DS.'com_gnudoor'.DS.'models'.DS.'calendar.php' );
require_once ( JPATH_BASE .DS.'components'.DS.'com_gnudoor'.DS.'models'.DS.'event.php' );

				
		
		$cal = new calendar;
		$cal->timezone=$config[0]['timezone'];
		
		JRequest::setVar('block_same_day',$config[0]['block_same_day']);
		
		if ($config[0]['calendar_message']) {
			JRequest::setVar('calendar_message',$config[0]['calendar_message']);
		}
		
		if ($config[0]['create_message']) {
			JRequest::setVar('create_message',$config[0]['create_message']);
		}
		
		$calprobs = 0;
		foreach($cals as $test) {
			$path_parts = pathinfo($test);
			if ($path_parts['dirname'] == '.') {
				#the cal is in the component subdir so add relevant info to path
$realpath = JPATH_SITE.DS.'components'.DS.'com_gnudoor'.DS.$test;
				$test = $realpath;
			}
			if (file_exists($test)) {
			} else {
				$calprobs = 1;
			}
		}
		
		if ($calprobs == 0) {

			$cal->parseCalendar($cals);
			$cal->kTimeslots = $kTimeslots;
//			$model->parseCalendar($cals);
//			$this->kTimeslots = $kTimeslots;
			
			JRequest::setVar('timezone',$config[0]['timezone']);		
			JRequest::setVar('timeslots',$kTimeslots);
			JRequest::setVar('days',Array("Sun","Mon","Tue","Wed","Thur","Fri","Sat"));
			JRequest::setVar('cal',$cal);
			JRequest::setVar('treatments',$kTreatments);
			JRequest::setVar('view','appointments');
			if (JRequest::getVar('task') == "create") {
			
				JRequest::setVar('layout','create');
			} else {
				JRequest::setVar('layout','default');	
			}
			
        	parent::display();
		} else {
			//probs with the calendar path load error display....
			$this->setMessage( JText::sprintf( 'It appears the calendars on this server are not configured correctly.', $n ) );
			$this->setRedirect('index.php?option=com_gnudoor&controller=appointments&task=error');
		}
    }
	

    
    function save() {
		JRequest::setVar('view','appointments');
		$db =& JFactory::getDBO();
		
		$query = "select * from #__pbbooking_customfields";
		$db->setQuery($query);
		$customfields = $db->loadAssocList();
		
	
		//echo 'saving event';
		$firstname=JRequest::getVar('firstname');
		$lastname=JRequest::getVar('lastname');
		$date=JRequest::getVar('date');
		$timeslot=JRequest::getVar('timeslot');
		$email=JRequest::getVar('email');
		$massage=JRequest::getVar('massage');
		$mobile = JRequest::getVar('mobile');

		$query = 'SELECT * FROM #__pbbooking_slots order by id';
		$db->setQuery( $query );
		$kTimeslots = $db->loadAssocList();
	
		$query = "SELECT path from #__pbbooking_cals where in_cal=1";
		$db->setQuery($query);
		$cals = $db->loadResultArray();
		
		$query="SELECT * from #__pbbooking_treatments";
		$db->setQuery($query);
		$kTreatments = $db->loadAssocList();
require_once ( JPATH_BASE .DS.'components'.DS.'com_gnudoor'.DS.'models'.DS.'calendar.php' );
require_once ( JPATH_BASE .DS.'components'.DS.'com_gnudoor'.DS.'models'.DS.'event.php' );
		
	
		$cal = new calendar;
		
		$query = "SELECT * from #__pbbooking_config";
		$db->setQuery($query);
		$config = $db->loadAssocList();
		
		$cal->timezone=$config[0]['timezone'];
		$cal->parseCalendar($cals);
		$cal->kTimeslots = $kTimeslots;
		JRequest::setVar('timezone',$config[0]['timezone']);
		
		//a final check to see if timeslot is busy
		if ($cal->isFree(date_create($date),$timeslot)) {
			$event = new event;
			$event->kTimeslots = $kTimeslots;
			$event->setProperties(date_create($date),$timeslot,$kTreatments[$massage]['duration'],
							$kTreatments[$massage]['name'].' for '.$firstname.' '.$lastname);
						
			//write the event to the database waiting for validation
			$query = sprintf("INSERT into #__pbbooking_pending (firstname,lastname,email,date,timeslot,massage,verified,mobile) values
							('%s','%s','%s','%s',%s,%s,0,'%s')",mysql_real_escape_string($firstname),
																mysql_real_escape_string($lastname),
																mysql_real_escape_string($email),
																mysql_real_escape_string($date),
																mysql_real_escape_string($timeslot),
																mysql_real_escape_string($massage),
																mysql_real_escape_string($mobile));
			$result = $db->Execute($query);
			
			if ($result) {
				//get the id of the inserted record
				$sql = sprintf("select * from #__pbbooking_pending where email = '%s' and date='%s' and timeslot=%s",
							$email,$date,$timeslot);
				$db->setQuery($sql);
				$booking = $db->loadAssocList();
				
				foreach(array_keys($_POST) as $key) {
					$data = $_POST[$key];
					$i= 0;
					foreach($customfields as $field) {
						if ($field['varname'] == $key) {
							$sql = sprintf('insert into #__pbbooking_customfields_data (customfield_id,pending_id,data) values (
								%s,%s,"%s")',mysql_real_escape_string($field['id']),
											mysql_real_escape_string($booking[0]['id']),
											mysql_real_escape_string($data));
							$db->Execute($sql);
						}
					}
					
				}
								
				JRequest::setVar('layout','success');
				$db =& JFactory::getDBO();		
				$sql = "select * from #__pbbooking_config";
				$db->setQuery( $sql );
				$dbconfig = $db->loadAssocList();
				
				$mailer =& JFactory::getMailer();
				$config =& JFactory::getConfig();
				$mailer->setSender($dbconfig[0]['sender_email']);
				$mailer->addRecipient($email);
				$mailer->addBCC($dbconfig[0]['sender_email']);
				$mailer->setSubject($dbconfig[0]['email_subject']);
				$mailer->isHTML(true);
								
				$urlstring = sprintf("%s/index.php?option=com_gnudoor&controller=appointments&task=validate&id=%s&email=%s",
						$dbconfig[0]['site_url'],$booking[0]['id'],$email);
				$temp = str_replace('|*URL*|',$urlstring,$dbconfig[0]['email_body']);

				$mailer->setBody($temp);
				$mailer->Send();
			} else {
				JRequest::setVar('layout','fail');
			}			
			
			//event written now redirect
			parent::display();
		} 
	}
	
	function validate() {
		JRequest::setVar('view','appointments');
		$pendingid = JRequest::getVar('id');
		$email = JRequest::getVar('email');
		
		$sql = "select * from #__pbbooking_pending where id = ".mysql_real_escape_string($pendingid);
		
		$db =& JFactory::getDBO();
		$db->setQuery( $sql );
		$dbpendingevents = $db->loadAssocList();
		
		$sql ="select * from #__pbbooking_customfields";
		$db->setQuery($sql);
		$customfields = $db->loadAssocList();
		
		$sql = "select * from #__pbbooking_customfields_data where pending_id =".mysql_real_escape_string($pendingid);
		$db->setQuery($sql);
		$customdata = $db->loadAssocList();
		
		$eventdesc = Array();
		
		#echo "customdata = ".print_r($customdata)."<br>";
		#echo "customfields = ".print_r($customfields)."<br>";
		
		foreach ($customdata as $data) {
			foreach ($customfields as $field) {
				if ($field['id'] == $data['customfield_id']) {
					$eventdesc[] = array('varname' => $field['varname'],'data' => $data['data']);
				}
			}
		}
		
		#echo print_r($eventdesc);
		
		
		if (count($dbpendingevents) == 0 || $dbpendingevents[0]['email'] != $email) {
			//there has been a problem
			JRequest::setVar('layout','fail');
			parent::display();		
		} else {
			//valid event
			$temp = $dbpendingevents[0];
			
			$query = 'SELECT * FROM #__pbbooking_slots order by id';
			$db->setQuery( $query );
			$kTimeslots = $db->loadAssocList();
			
			$query = "SELECT path from #__pbbooking_cals where in_cal=1";
			$db->setQuery($query);
			$cals = $db->loadResultArray();
			
			$query = "SELECT * from #__pbbooking_config";
			$db->setQuery($query);
			$config = $db->loadAssocList();
require_once ( JPATH_BASE .DS.'components'.DS.'com_gnudoor'.DS.'models'.DS.'calendar.php' );
require_once ( JPATH_BASE .DS.'components'.DS.'com_gnudoor'.DS.'models'.DS.'event.php' );
			
			$cal = new calendar;
			$cal->timezone=$config[0]['timezone'];
			$cal->parseCalendar($cals);
			$cal->kTimeslots = $kTimeslots;
			JRequest::setVar('timezone',$config[0]['timezone']);
			
			
			if ($cal->isFree(date_create($temp['date']),$temp['timeslot'])) {
				$query="SELECT * from #__pbbooking_treatments";
				$db->setQuery($query);
				$kTreatments = $db->loadAssocList();
				
				$event = new event;
				$event->kTimeslots = $kTimeslots;
				$event->setProperties(date_create($temp['date']),$temp['timeslot'],$kTreatments[$temp['massage']]['duration'],
							$kTreatments[$temp['massage']]['name'].' for '.$temp['firstname'].' '.$temp['lastname']);
				$event->setDescription($eventdesc);
									
				$query ="SELECT * FROM #__pbbooking_cals where out_cal = 1";
				$db->setQuery($query);
				$cals = $db->loadAssocList();
					
				$cal = new calendar;
				$cal->timezone=$config[0]['timezone'];
				$cal->writeEvent($event,$cals[0]['path']);
				
				// update record in database
				$query = sprintf("update #__pbbooking_pending set verified = 1 where id = %s",mysql_real_escape_string($pendingid));
				$db->setQuery($query);
				$db->Execute($query);
				
				$mailer =& JFactory::getMailer();
				$mailerconfig =& JFactory::getConfig();
				$mailer->setSender($config[0]['sender_email']);
				$mailer->addRecipient($email);
				$mailer->setSubject('PBBooking: New Validated Appointment');
				$mailer->isHTML(true);
				$mailer->setBody('There is a new validated appointment in the diary.');
				$mailer->Send();
				
				JRequest::setVar('layout','validated');
				parent::display();
			} else {
				JRequest::setVar('layout','fail');
				parent::display();
			}
			
		}
		
	}
	
	function error() {
		//$this->setLayout('fail');
		JRequest::setVar('view','appointments');
		JRequest::setVar('layout','error');
		parent::display();
	}
	
//	function isFree($date,$timeslot){
//
//		global $timezone;
//		date_default_timezone_set($this->timezone);
//		
//		$eventstart = clone $date;
//		$eventend = clone $date;
//		$eventstart->setTime($this->kTimeslots[$timeslot]['start_hour'],$this->kTimeslots[$timeslot]['start_min']);
//		$eventend->setTime($this->kTimeslots[$timeslot]['end_hour'],$this->kTimeslots[$timeslot]['end_min']);
//			
//		$free = true;
//		foreach($this->events as $event) {
//			//check for normal events
//			if ($event->dtend >= $eventstart && $event->dtend <= $eventend) {
//				$free = false;
//			}
//			
//			//check for multi day events
//			if ($event->dtstart <= $eventstart && $event->dtend >= $eventend) {
//				$free = false;
//			}
//			
//			//check for recurrance
//			$checkrecur = false;
//			if ($event->recurring) {
//				if (gettype($event->recurring['until']) != "integer") {
//					$until = $event->recurring['until'];
//					if ($until > $eventstart) {
//						$checkrecur = true;
//					}
//				} else {
//					$checkrecur = true;
//				}
//				
//				if ($checkrecur) {
//					$checkstart = clone $event->dtstart;
//					$checkend = clone $event->dtend;
//					while ($checkstart <= $eventstart) {
//						if ($checkend >= $eventstart && $checkend <= $eventend) {
//							$free = false;
//						}
//						$modstring = sprintf("+%s day",7*$event->recurring['interval']);
//						$checkstart->modify($modstring);
//						$checkend->modify($modstring);
//					}
//				}
//			}
//		}
//		return $free;
//	}
//
//	function writeEvent($event,$calfile) {
//		global $timezone;
//		date_default_timezone_set($this->timezone);
//		
//		global $kOutcal;
//		//BEGIN:VEVENT
//		//DTEND;VALUE=DATE-TIME:20100426T172429Z
//		//DTSTART;VALUE=DATE-TIME:20100426T162429
//		//SUMMARY:New Event
//		//END:VEVENT
//		
//		$path_parts = pathinfo($calfile);
//		if ($path_parts['dirname'] == '.') {
//			#the cal is in the component subdir so add relevant info to path
//			$realpath = JPATH_SITE.DS.'components'.DS.'com_gnudoor'.DS.$calfile;
//			$calfile = $realpath;
//		}
//		
//		$file = @fopen($calfile,"r");
//		$lines = Array();
//		$i = 0;
//		$insert=0;
//		while(!feof($file)) {
//			//read entire file into memory and if line == BEGIN:VTIMEZONE then note the line in $i
//			$line = fgets($file);
//			if (preg_match("/^BEGIN:VTIMEZONE/",$line) == 1) {
//				$insert=$i;
//			}
//			$i++;
//			$lines[]=$line;
//		}
//		fclose($file);
//		
//		//slice array from insert to end
//		//add elements recursively to end of array and merge again
//		$arr1 = array_slice($lines,0,$insert);
//		$arr2 = array_slice($lines,$insert,(count($lines)-$insert));
//		//pop new elements to end of $arr1
//		$arr1[] = "BEGIN:VEVENT\n";
//		$arr1[] = sprintf("DTEND;VALUE=DATE-TIME:%sT%sZ\n",date_format($event->dtend,'Ymd'),date_format($event->dtend,'His'));
//		$arr1[] = sprintf("DTSTART;VALUE=DATE-TIME:%sT%s\n",date_format($event->dtstart,'Ymd'),date_format($event->dtstart,'His'));
//		$arr1[]=sprintf("SUMMARY:%s\n",$event->summary);
//		$arr1[]="DESCRIPTION:$event->description\n";
//		$arr1[]="END:VEVENT\n";
//		
//		$lines = array_merge($arr1,$arr2);
//		
//		$file = @fopen($calfile,"w");
//		foreach($lines as $line) {
//			fwrite($file,$line);
//		}
//		
//		fclose($file);
//	}
//
//	function _parseCalendar($cals) {
//		global $timezone;
//		date_default_timezone_set($this->timezone);
//	
//		$events = Array();
//		
//		foreach($cals as $cal)
//		{
//			$path_parts = pathinfo($cal);
//			if ($path_parts['dirname'] == '.') {
//				#the cal is in the component subdir so add relevant info to path
//				$realpath = JPATH_SITE.DS.'components'.DS.'com_gnudoor'.DS.$cal;
//				$cal = $realpath;
//			}
//			
//			$file = @fopen($cal,"r");
//		
//			$string = "";
//	
//			$inevent = false;
//			$i = 0;
//	
//	
//			$curr_summary = "";
//			$curr_dtend = "";
//			$curr_dtstart = "";
//			$recurring = false;
//			$recarr = Array();
//	
//			while(!feof($file)) {
//		
//				$line = fgets($file);
//		
//				if (preg_match("/^BEGIN:VEVENT/",$line)==1) {
//					//we have started an event
//					$inevent = true;
//					$i = $i +1;
//				}
//		
//				if ($inevent) {
//					if (preg_match("/^SUMMARY:/",$line) == 1) {
//						$curr_summary = str_replace('SUMMARY:',"",$line);
//					}
//					if (preg_match("/^DTEND;TZID=/",$line) == 1) {
//						//this captures on cals where we have TZID in the code
//						$temp = str_replace('DTEND;TZID='.$this->timezone.':',"",$line);
//						$curr_dtend= date_create($temp);
//					}
//			
//					if (preg_match("/^DTSTART;TZID=/",$line) == 1) {
//						//echo this captues on cals where we have TZID in the code
//						$temp = str_replace("DTSTART;TZID=".$this->timezone.":","",$line);
//						$curr_dtstart= date_create($temp);
//					}
//	
//					if (preg_match("/^DTEND;VALUE=DATE-TIME/",$line) == 1) {
//						//this captures on cals where we have zulu time
//						$temp = str_replace('DTEND;VALUE=DATE-TIME:',"",$line);
//						$temp1=str_replace('Z',"",$temp);
//						$curr_dtend= date_create($temp1);
//					}
//					
//					if (preg_match("/^DTSTART;VALUE=DATE-TIME/",$line) == 1) {
//						//this captures on cals where we have zulu time
//						$temp = str_replace('DTSTART;VALUE=DATE-TIME:',"",$line);
//						$curr_dtstart= date_create($temp);
//					}
//					
//					if (preg_match("/^RRULE:/",$line)==1) {
//						//we are in a recurring event
//						$temp = str_replace('RRULE:',"",$line);
//						$recarr = explode(";",$temp);
//						$recurring = true;
//					}
//	
//			
//					if (preg_match("/^END:VEVENT/",$line) == 1) {
//						//we have reached the close of the event
//						$inevent = false;
//						//$event = Array("summary" => $curr_summary, "dtend" => $curr_dtend, "dtstart"=>$curr_dtstart);
//						$event = new event();
//						$event->summary = $curr_summary;
//						$event->dtend = $curr_dtend;
//						$event->dtstart = $curr_dtstart;
//						if ($recurring) {
//							$recurring = false;
//							$interval = str_replace('INTERVAL=',"",$recarr[1]);
//							
//							//is until defined?
//							if (isset($recarr[2])) {
//								if (preg_match("/^UNTIL=/",$recarr[2])==1) {
//									$temp=str_replace('Z',"",$recarr[2]);
//									$untilstring = str_replace("UNTIL=","",$temp);
//									$untildate= date_create($untilstring);
//									$event->recurring = Array ("frequency"=>"week","interval"=>$interval,"until"=>$untildate);
//								}
//							} else {
//								$event->recurring = Array ("frequency"=>"week","interval"=>$interval,"until"=>0);
//							}
//							
//							
//						}
//						$events[]=$event;
//					}
//				}	
//			}
//		}
//		
//		foreach($events as $row) {
//			$dtstart[]=$row->dtstart;
//		}
//	
//		//gives me an array of events going newest to oldest
//		if (count($events) > 0) {
//			array_multisort($dtstart,SORT_DESC,$events);
//		}
//		
//		$this->events = $events;
//	}
//	
//	function setProperties($date,$timeslot,$duration,$summary) {
//		global $kTimeslots;
//		$this->summary = $summary;
//		$dtstart = clone $date;
//		$dtstart->setTime($this->kTimeslots[$timeslot]['start_hour'],$this->kTimeslots[$timeslot]['start_min']);
//		$dtend = clone $dtstart;
//		$dtend->modify('+'.$duration.' minutes');
//		$this->dtend = $dtend;
//		$this->dtstart = $dtstart;
//	}
//	
//	function setDescription($customfields) {
//		#function to set the description to contact a list of custom fields
//		if (count($customfields>0)) {
//			foreach ($customfields as $field) {
//				$this->description .= sprintf('%s = %s\n',$field['varname'],$field['data']);
//			}
//		}
//	}

}

?>